package com.rdr.randDinnner.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 根据经纬度获取地址
 */
public class AddressUtils {
    static String secretKey = "K4KBZ-RIN6R-2WUWD-WMSO6-MAFTH-MBB75";

    /**
     * @param lat 纬度
     * @param lng 经度
     * @return
     */
    public static Result getAddress(String lat, String lng) throws IOException {
        JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result");
        System.out.println(obj);
        Result result = JsonUtil.fromJson(obj.toString(), Result.class);

        return result;
    }

    public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
        String urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
        System.out.println("请求经纬度url:" + urlString);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        String line;
        String res = "";
        while ((line = in.readLine()) != null) {
            res += line + "\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(res);
        System.out.println(jsonObject);
        return jsonObject;
    }


    public static void main(String[] args) throws IOException {
        Result address = getAddress("39.074994", "121.671244");
        System.out.println(address.getAdInfo().getCity());

    }

}